﻿using System;
using System.IO;
using System.Web.Mvc;

namespace BlueSky.Web.ActionResults
{
    /// <summary>
    /// Download result class.
    /// </summary>
    public class DownloadResult : ActionResult
    {
        /// <summary>
        /// File virtual path.
        /// </summary>
        public String VirtualFilePath
        {
            get;
            set;
        }

        /// <summary>
        /// File alias name.
        /// </summary>
        public String AliasFileName
        {
            get;
            set;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="virtualFilePath">File virtual path.</param>
        public DownloadResult(string virtualFilePath) : 
            this(virtualFilePath, Path.GetFileName(virtualFilePath))
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="virtualFilePath">File virtual path.</param>
        /// <param name="aliasFileName">File alias name.</param>
        public DownloadResult(string virtualFilePath, string aliasFileName)
        {
            VirtualFilePath = virtualFilePath;
            AliasFileName = aliasFileName;
        }

        public override void ExecuteResult(ControllerContext context)
        {            
            if (!String.IsNullOrEmpty(AliasFileName))
            {
                context.HttpContext.Response.AddHeader("content-disposition", string.Concat("attachment; filename=", AliasFileName));
            }
            string filePath = context.HttpContext.Server.MapPath(VirtualFilePath);
            context.HttpContext.Response.TransmitFile(filePath);
        }
    }
    
}
